import axios from 'axios';
import { ElMessage } from 'element-plus'

let baseUrl = import.meta.env.VITE_APP_BASE_API

const CancelToken = axios.CancelToken;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: baseUrl,
    // 超时
    timeout: import.meta.env.VITE_TIMEOUT
})

// axios.defaults.withCredentials = true;
// 添加请求拦截器
service.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么 传token
    //let token = localStorage.getItem("token");
    //config.headers.common['token'] = token;  //Authorization
    return config;
}, function (error) {
    console.log('error',error);
    // 对请求错误做些什么
    return Promise.reject(error);
});
/**
 * @响应拦截
 */
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;

    if (code !== 200) {
        return Promise.reject(res)
    }
    /**
     * @code 登录过期 token验证失败 根据后端调
     */
    if (code === 401) {
        // router.push("/login")
    }
    return res.data
}, error => {
    console.log("error: ",error)
    // 对请求错误做些什么
    let { message } = error;
    if (message == "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({ message: message, type: 'error', duration: 3 * 1000 })
})

let configs_ENC = {
    headers: { 'enc': false }
}
//处理是否加密数据
let isEncryptionParam = (params) => {
    return params

}
export const GET = async (url, params) => {
    try {
        params = isEncryptionParam(params)
        return await service.get(`${url}`, {
            params: params,
            headers: configs_ENC.headers
        });
    } catch (error) {
        return error;
    }
}
export const POST = async (url, params) => {
    try {
        params = isEncryptionParam(params)
        return await service.post(`${url}`, params, configs_ENC);
    } catch (error:any) {
        return error.data;
    }
}
export const PUT = async (url, params) => {
    try {
        params = isEncryptionParam(params)
        return await service.put(`${url}`, params, configs_ENC);
    } catch (error) {
        return error;
    }
}
export const DELETE = async (url, params) => {
    try {
        params = isEncryptionParam(params)
        return await service.delete(`${url}`, {data: params, headers: configs_ENC.headers});
    } catch (error:any) {
        return error.data;
    }
}


/**
 * @文件类型提交方法
 */
let configs = {
    headers: { 'Content-Type': 'multipart/form-data' },

}
export const FileSubmit = async (url, params, config) => {
    try {
        const data = await service.post(`${url}`, params, {
            ...configs,
            cancelToken: new CancelToken(function executor(c) {
                config.setCancel && config.setCancel(c)
            }),
            onUploadProgress: (e) => {
                if (e.total > 0) {
                    e.percent = e.loaded / e.total * 100;
                }
                config.onProgress && config.onProgress(e)
            },

        });
        return data;
    } catch (error:any) {
        return error.data;
    }
}